<template>
    <div class='addOrEdit'>
        <el-dialog :visible.sync="addOrEditVisible" width="700px" @close='handleClose' :lock-scroll="false">
            <span class="title" slot="title">{{title}}产品</span>
            <div class="add">
                <el-form :model="addForm" :rules="rules" ref="addForm" label-width="125px" size="mini"
                    :hide-required-asterisk="true">
                    <el-form-item prop="other">
                        <template slot='label'>
                            <span style="color: red">*</span>
                            产品
                        </template>
                        <el-select v-model="addForm.other" filterable remote placeholder="请选择"
                            :remote-method="remoteMethod" :loading="proLoading" @visible-change='visibleChange'
                            @change="productChange">
                            <el-option v-for="item in cpOptions" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="产品数据" v-show="addForm.other">
                        <div class="productData">
                            <span>库存单位：{{temp.unitName}}</span>
                            <span>当前库存数量：{{temp.stock}}</span>
                        </div>
                    </el-form-item>
                    <el-form-item prop="number">
                        <template slot='label'>
                            <span style="color: red">*</span>
                            入库数量
                        </template>
                        <el-input-number v-model="addForm.number" controls-position="right" size="mini">
                        </el-input-number>
                    </el-form-item>
                    <!-- ====================自定义==================== -->
                    <el-form-item v-for='(item, i) in customFiledList' :key="i" :label='item.chineseName'
                        :prop="item.id" v-show='hiddenRule(item)'>
                        <el-checkbox-group v-show="false" v-model="addForm[item.id]"></el-checkbox-group>
                        <template slot='label'>
                            <span style="color: red" v-show="requireRsterisk(item)">*</span>
                            {{ item.chineseName }}
                            <el-tooltip class="item" effect="dark" :content="item.tips" placement="top"
                                v-show='item.tips'>
                                <span class="iconfont icon-wenhao wenhao"></span>
                            </el-tooltip>
                        </template>
                        <formLibrary :formItem='item' @formItemHandle='formItemHandle' :defaultData="defaultData"
                            @uploadProgress='uploadProgress' ref='formLibrary'></formLibrary>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="mini" @click='handleClose'>取 消</el-button>
                <el-button type="primary" size="mini" @click='addProduct'>确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {
        pOther
    } from '@/api/baseController'
    import {
        loginUserMess
    } from '@/api/loginController'
    import {
        customFieldOther,
        fillFieldMess
    } from '@/api/customFieldController'
    import formLibrary from '@/components/formLibrary'
    export default {
        data() {
            var number = (rule, value, callback) => {
                if (value == 0) {
                    return callback(new Error('入库数量必须大于0'));
                } else if (value == undefined) {
                    return callback(new Error('入库数量不能为空!'));
                } else if (value > 9007199254740991) {
                    return callback(new Error('入库数量必须小于等于9007199254740991'));
                } else {
                    callback()
                }
            };
            return {
                addForm: {
                    other: '',
                    number: 1
                },
                rules: {
                    other: [{
                        required: true,
                        message: '产品不能为空！'
                    }],
                    number: [{
                        required: true,
                        validator: number
                    }]
                },
                title: '',
                rowIndex: 0,
                cpOptions: [],
                proLoading: false,
                addOrEditVisible: false,
                temp: {},
                customFiledList: [],
                defaultData: [], // 自定义字段值
                customFiledData: [],
                customState: true, // 判断单选/复选 选值是否正确
                customErrorLabel: '', // 选值错误提示语
                // 关联属性信息
                relevanceProp: [],
                productInfo: {},
                userMess: {},
                uploadFlag: true
            }
        },
        components: {
            formLibrary
        },
        watch: {
            addForm: {
                handler() {
                    this.hiddenRule('')
                },
                deep: true,
            }
        },
        mounted() {},
        methods: {
            // 自定义字段
            getCustomFieldOther() {
                customFieldOther({
                    type: 'stockMsg'
                }).then(res => {
                    this.customFiledList = []
                    this.relevanceProp = []
                    if (res.code == 200) {
                        // 自定义字段数据
                        res.data.map(item => {
                            item.customFieldMess.objectsValue = item.objectsValue
                            this.customFiledList.push(item.customFieldMess)
                        })
                        // 添加自定义字段的校验规则(是否必填)
                        this.customFiledList.map(item => {
                            let r = item.hidden
                            item.hidden = r.replace(/\${出入库明细./g, 'formItemData["').replace(/\}/g, '"]')
                                .replace(/\${用户信息./g, 'userFormItemData["')
                            item.id = item.id + ''
                            let obj = {}
                            if (JSON.parse(item.fieldAttribute).required && item.fieldType != 'inputNumber') {
                                obj[item.id] = [{
                                    required: true,
                                    message: item.chineseName + '不能为空'
                                }]
                            }else if (item.fieldType == 'inputNumber'){
                                const numberRule = (rule, v, callback) => {
                                    let tempValue = ''
                                    let index = String(this.addForm[item.id]).indexOf('.')
                                    tempValue = index != -1 ? String(this.addForm[item.id]).slice(0,index) : String(this.addForm[item.id])
                                    if (!this.addForm[item.id] && item.isRequired) {
                                        return callback(new Error(`${item.chineseName}不能为空！`));
                                    }else if(tempValue.length > 10){
                                        return callback(new Error('整数位最多支持10位数字'));
                                    }else if(this.addForm[item.id] != undefined && !(/^[0-9]+(.[0-9]{1,6})?$/.test(this.addForm[item.id]))){
                                        return callback(new Error('小数点后最多保留6位数字'));
                                    }else {
                                        callback()
                                    }
                                }
                                obj[item.id] = [{
                                    validator: numberRule,
                                    trigger:'blur'
                                }]
                            }
                            this.rules = Object.assign(this.rules, obj)
                            if (item.fieldType == 'relevanceProp') {
                                this.relevanceProp.push({
                                    id: item.id,
                                    objectFieldId: item.objectFieldId,
                                    type: item.correlationField
                                })
                            }
                        })
                        this.getLoginUserMess()
                    }
                })
            },
            // 用户信息
            getLoginUserMess(data) {
                loginUserMess(data).then(res => {
                    this.loading = false
                    if (res.code == 200) {
                        this.userMess = res.data
                    }
                })
            },
            // 关联对象-字段信息
            getFillFieldMess(data, fillRule, n) {
                fillFieldMess(data).then(res => {
                    this.defaultData = []
                    for (let key in this.addForm) {
                        if (Number(key)) {
                            this.defaultData.push({
                                customFieldId: key,
                                value: this.addForm[key]
                            })
                        }
                    }
                    if (res.code == 200) {
                        // 如果该条数据有自定义字段
                        if (res.data.customFieldVos != null) {
                            /* 
                                遍历关联对象的填充规则
                                遍历该条数据的自定义字段列表
                                将填充规则中的来源值(from) 赋给 指定控件(to)
                            */
                            fillRule.map(item => {
                                let dataArr = []
                                let f = res.data.customFieldVos.find(res => {
                                    return res.customFieldId == item.from
                                })
                                if (f != undefined) {
                                    res.data.customFieldVos.map(k => {
                                        if (k.customFieldId == item.from) {
                                            this.addForm[item.to] = k.value
                                            this.defaultData = this.defaultData.filter(j => j
                                                .customFieldId != item.to)
                                            this.defaultData.push({
                                                customFieldId: item.to,
                                                value: k.value
                                            })
                                        }
                                    })
                                } else {
                                    this.addForm[item.to] = ''
                                    this.defaultData.map(k => {
                                        if (k.customFieldId == item.to) {
                                            let d = this.customFiledList.find(res => {
                                                return res.id == item.to
                                            })
                                            if (d.fieldType == 'picture' || d.fieldType ==
                                                'upload' || d.fieldType == 'selectChecked') {
                                                dataArr.push({
                                                    customFieldId: k.customFieldId,
                                                    value: "[]"
                                                })
                                            } else {
                                                dataArr.push({
                                                    customFieldId: k.customFieldId,
                                                    value: ""
                                                })
                                            }
                                        } else {
                                            dataArr.push({
                                                customFieldId: k.customFieldId,
                                                value: k.value
                                            })
                                        }
                                    })
                                    this.defaultData = dataArr
                                }
                            })
                        } else {
                            fillRule.map(item => {
                                let dataArr = []
                                this.addForm[item.to] = ''
                                this.defaultData.map(k => {
                                    if (k.customFieldId == item.to) {
                                        let d = this.customFiledList.find(res => {
                                            return res.id == item.to
                                        })
                                        if (d.fieldType == 'picture' || d.fieldType ==
                                            'upload' || d.fieldType == 'selectChecked') {
                                            dataArr.push({
                                                customFieldId: k.customFieldId,
                                                value: "[]"
                                            })
                                        } else {
                                            dataArr.push({
                                                customFieldId: k.customFieldId,
                                                value: ""
                                            })
                                        }
                                    } else {
                                        dataArr.push({
                                            customFieldId: k.customFieldId,
                                            value: k.value
                                        })
                                    }
                                })
                                this.defaultData = dataArr
                            })
                        }
                        // 关联属性赋值
                        this.relevanceProp.map(item => {
                            if (item.objectFieldId == n) {
                                this.addForm[item.id] = res.data[item.type]
                                this.defaultData = this.defaultData.filter(j => j.customFieldId != item
                                    .id)
                                this.defaultData.push({
                                    customFieldId: item.id,
                                    value: res.data[item.type]
                                })
                            }
                        })
                    }
                })
            },
            // 自定义表单项数据--表单子组件传递的值
            formItemHandle(d) {
                // 子组件的值赋给表单
                this.$set(this.addForm, d.name, d.value)
                // 操作的是关联对象
                if (d.relevanceObject != undefined) {
                    if (d.relevanceObject.id) {
                        let data = {
                            id: d.relevanceObject.id,
                            type: d.relevanceObject.businessObject
                        }
                        this.getFillFieldMess(data, d.relevanceObject.fillRule, d.name)
                    } else {
                        this.customFiledList.map(item => {
                            if (item.objectFieldId == d.name) {
                                this.addForm[item.id] = ''
                                this.defaultData.map(k => {
                                    if (k.customFieldId == item.id || k.customFieldId == d.name) {
                                        k.value = ''
                                    }
                                })
                            }
                        })
                        for (let key in this.addForm) {
                            let ind = this.defaultData.findIndex(res => {
                                return res.customFieldId == key
                            })
                            if (ind != -1) {
                                this.$set(this.defaultData, ind, {
                                    customFieldId: key,
                                    value: this.addForm[key]
                                })
                            } else {
                                this.defaultData.push({
                                    customFieldId: key,
                                    value: this.addForm[key]
                                })
                            }
                        }
                    }
                }
            },
            // 自定义隐藏设置--隐藏条件触发
            hiddenRule(d) {
                let formItemData = {
                    '出/入库数量': this.addForm.number
                }
                let userFormItemData = {
                    '账号': this.userMess.account,
                    '姓名': this.userMess.name,
                    '手机号': this.userMess.mobile,
                    '角色': this.userMess.role,
                }
                this.customFiledList.map(item => {
                    if (formItemData[item.chineseName] == undefined) {
                        if (this.addForm[item.id] != undefined) {
                            formItemData[item.chineseName] = this.addForm[item.id]
                        } else {
                            formItemData[item.chineseName] = ''
                        }
                    }
                    if (userFormItemData[item.chineseName] == undefined) {
                        if (this.addForm[item.id] != undefined) {
                            userFormItemData[item.chineseName] = this.addForm[item.id]
                        } else {
                            userFormItemData[item.chineseName] = ''
                        }
                    }
                })
                let state = null
                try {
                    state = !eval(d.hidden)
                } catch {
                    state = true
                }
                //必填项字段若是被隐藏不校验
                if (this.rules[d.id]) {
                    if(d.fieldType == 'inputNumber'){
                        if(JSON.parse(d.fieldAttribute).required){ //inputNumber 必填 && 切换触发隐藏条件
                            d.isRequired = state
                        }
                    }else{
                        this.rules[d.id][0].required = state
                    }
                }
                return state
            },
            requireRsterisk(d) {
                if (this.rules[d.id]) {
                    if(d.fieldType == 'inputNumber'){
                        return JSON.parse(d.fieldAttribute).required || false
                    }else{
                        return this.rules[d.id][0].required || false
                    }
                }
            },
            customData(v, data) {
                if (Number(v)) {
                    let id = ''
                    data.map(item => {
                        if (item.value == v) {
                            id = item.label
                        }
                    })
                    return id
                } else {
                    return v
                }
            },
            // 附件/图片上传是否完成
            uploadProgress(s) {
                this.uploadFlag = s
            },
            //产品下拉
            getPOther(data) {
                pOther(data).then(res => {
                    this.proLoading = false
                    if (res.code == 200) {
                        this.productData = res.data
                        this.cpOptions = res.data.map(item => {
                            return {
                                value: item.id,
                                label: item.code + '-' + item.name + '-' + item.specification
                            };
                        });
                    }
                })
            },
            productChange(id) {
                this.temp = this.productData.find(p => p.id == id)
            },
            getInfo(productData, cpOptions) {
                this.productData = productData
                this.cpOptions = cpOptions
            },
            //下拉框打开时
            visibleChange(flag) {
                if (flag) this.remoteMethod('')
            },
            //添加产品--产品框
            remoteMethod(query) {
                this.proLoading = true;
                this.getPOther({
                    name: query
                })
            },
            add(payload) {
                this.getCustomFieldOther()
                if (payload.title == 'add') {
                    this.title = '添加'
                } else {
                    this.title = '编辑'
                    this.productChange(payload.row.productId)
                    this.addForm.other = payload.row.productId
                    this.addForm.number = payload.row.handleNum
                    this.rowIndex = payload.rowIndex
                    this.customFiledData = []
                    this.defaultData = []
                    if (payload.row.customFieldVos != null) {
                        payload.row.customFieldVos.map(item => {
                            this.$set(this.addForm, item.customFieldId, item.value)
                            this.customFiledData.push({
                                customFieldId: item.customFieldId,
                                value: item.value
                            })
                            this.defaultData.push({
                                customFieldId: item.customFieldId,
                                value: item.value
                            })
                        })
                    }
                }
                this.addOrEditVisible = true
                this.$nextTick(() => {
                    let bodyNode = document.querySelector('.add')
                    bodyNode.scrollTop = 0
                })
            },
            //确认添加
            addProduct() {
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        let productTable = {
                            productCode: this.temp.code,
                            productName: this.temp.name,
                            productSpecification: this.temp.specification || '-',
                            unit: this.temp.unitName,
                            minimum: this.temp.minimum || '-',
                            maximum: this.temp.maximum || '-',
                            safe: this.temp.safe || '-',
                            nowNum: this.temp.stock || '-',
                            productId: this.temp.id,
                            handleNum: this.addForm.number,
                            customFieldVos: []
                        }
                        // 关联对象后，判断单选框/复选框关联过来的值是否存在
                        this.customState = true
                        this.customErrorLabel = ''
                        this.customFiledList.map(item => {
                            // 单选框
                            if (item.fieldType == 'selectRadio') {
                                if (this.addForm[item.id] != '' && this.addForm[item.id] !=
                                    undefined) {
                                    let s = JSON.parse(item.checkBox).find(res => {
                                        return this.addForm[item.id] == res.value
                                    })
                                    if (s == undefined) {
                                        this.customState = false
                                        this.customErrorLabel = '【' + item.chineseName + '】选项值不正确'
                                    }
                                }
                            }
                            // 复选框
                            if (item.fieldType == 'selectChecked') {
                                if (this.addForm[item.id] != '' && this.addForm[item.id] !=
                                    undefined && this.addForm[item.id] != '[]') {
                                    JSON.parse(this.addForm[item.id]).map(k => {
                                        let s = JSON.parse(item.checkBox).find(res => {
                                            return res.value == k
                                        })
                                        if (s == undefined) {
                                            this.customState = false
                                            this.customErrorLabel = '【' + item.chineseName +
                                                '】选项值不正确'
                                        }
                                    })
                                }
                            }
                        })
                        if (this.customState) {
                            if (this.uploadFlag) {
                                this.$refs.formLibrary != undefined && this.$refs.formLibrary.map(k => {
                                    k.removeData('ok')
                                })
                                for (let key in this.addForm) {
                                    if (Number(key)) {
                                        this.customFiledList.forEach(item => {
                                            if (item.id == key && this.addForm[key] != null &&
                                                String(this.addForm[key]).length) {
                                                productTable.customFieldVos.push({
                                                    customFieldId: item.id,
                                                    value: this.addForm[key],
                                                    customFieldMess: item
                                                })
                                            }
                                        })
                                    }
                                }
                                this.$emit('getProductTable', {
                                    productTable,
                                    title: this.title,
                                    rowIndex: this.rowIndex
                                })
                                this.addOrEditVisible = false
                            } else {
                                this.utils.showMsg('正在上传，请稍后', 'warning')
                            }
                        } else {
                            this.utils.showMsg(this.customErrorLabel, 'error')
                        }
                    } else {
                        return false;
                    }
                })
            },
            handleClose() {
                this.addOrEditVisible = false
                this.addForm = {
                        other: '',
                        number: 1
                    },
                    this.$refs.addForm.resetFields()
                this.defaultData = []
                this.$refs.formLibrary != undefined && this.$refs.formLibrary.map(k => {
                    k.removeData('cancle')
                })
            }
        }
    }
</script>

<style lang="less" scoped>
    .addOrEdit {
        .add {
            padding: 30px 60px 30px 70px;
            border: 1px solid #e8e8e8;
            background-color: #fafafa;
            max-height: 470px;
            overflow-y: scroll;

            /deep/.el-form {
                width: 80%;
            }

            .productData {
                width: 100%;
                padding: 20px;
                background-color: rgb(242, 242, 242);
                display: flex;
                flex-direction: column;
                color: rgba(0, 0, 0, .85);
            }

            .el-form-item--mini.el-form-item:last-child {
                margin-bottom: 0;
            }
        }

        /deep/ .el-dialog__body {
            padding: 10px 40px;
        }

        /deep/ .el-dialog__footer {
            text-align: center;

            .el-button {
                padding: 7px 35px;
            }
        }
    }
</style>